<template>
  <HeaderTitle title="员工交收报表二 (手工帐)"></HeaderTitle>
  <div class="deliveryEnquiryPage">
    <div class="row searchBox">
      <div class="sbTitle">金成色选项</div>
      <div class="gtBox">
        <div v-for="(gold, index) in goldTypeInfo" :key="index" class="row">
          <div class="col-10 gtTitle" :class="{ goldChosen: gold.isChosen }">
            {{ gold.goldType }}
          </div>
          <div class="col-2 gtBtn" @click="toggleChoice(index)">
            <q-icon name="fa-solid fa-check" color="white" class="gtSVG" />
          </div>
        </div>
      </div>
      <div class="row sbTitle">日期范围</div>
      <div class="row dateRangeBox items-center">
        <div class="col-5">
          <q-input class="input-css" filled dense v-model="deliverDate">
            <template v-slot:prepend>
              <q-icon name="event" class="cursor-pointer">
                <q-popup-proxy>
                  <q-date
                    color="deep-purple-7"
                    v-model="deliverDate"
                    mask="YYYY-MM-DD HH:mm:ss"
                  >
                    <div class="row items-center justify-end">
                      <q-btn v-close-popup label="Close" color="primary" flat />
                    </div>
                  </q-date>
                </q-popup-proxy>
              </q-icon>
            </template>

            <template v-slot:append>
              <q-icon name="access_time" class="cursor-pointer">
                <q-popup-proxy>
                  <q-time
                    color="deep-purple-7"
                    v-model="deliverDate"
                    mask="YYYY-MM-DD HH:mm:ss"
                    format24h
                  >
                    <div class="row items-center justify-end">
                      <q-btn v-close-popup label="Close" color="primary" flat />
                    </div>
                  </q-time>
                </q-popup-proxy>
              </q-icon>
            </template>
          </q-input>
        </div>
        <!-- <input type="date" class="col-5" v-model="deliverDate" /> -->

        <!-- <q-select
            color="deep-purple-9"
            bg-color="white"
            filled
            v-model="sDate"
            :options="dateStart"
            dense
          >
            <template v-slot:prepend>
              <q-icon name="event" />
            </template>
          </q-select> -->

        <div class="col-auto drContent">至</div>
        <!-- <input type="date" class="col-5" v-model="completeDate" /> -->

        <div class="col-5">
          <q-input class="input-css" filled dense v-model="completeDate">
            <template v-slot:prepend>
              <q-icon name="event" class="cursor-pointer">
                <q-popup-proxy>
                  <q-date
                    color="deep-purple-7"
                    v-model="completeDate"
                    mask="YYYY-MM-DD HH:mm:ss"
                  >
                    <div class="row items-center justify-end">
                      <q-btn v-close-popup label="Close" color="primary" flat />
                    </div>
                  </q-date>
                </q-popup-proxy>
              </q-icon>
            </template>

            <template v-slot:append>
              <q-icon name="access_time" class="cursor-pointer">
                <q-popup-proxy>
                  <q-time
                    color="deep-purple-7"
                    v-model="completeDate"
                    mask="YYYY-MM-DD HH:mm:ss"
                    format24h
                  >
                    <div class="row items-center justify-end">
                      <q-btn v-close-popup label="Close" color="primary" flat />
                    </div>
                  </q-time>
                </q-popup-proxy>
              </q-icon>
            </template>
          </q-input>
        </div>

        <!-- <div class="col">
          <q-select
            color="deep-purple-9"
            bg-color="white"
            filled
            v-model="eDate"
            :options="dateEnd"
            dense
          >
            <template v-slot:prepend>
              <q-icon name="event" />
            </template>
          </q-select>
        </div> -->
      </div>
    </div>

    <div class="row searchBtnBox">
      <q-btn color="deep-purple-10" class="searchBtn" @click="searchInfo()"
        >搜寻</q-btn
      >
    </div>

    <div v-if="showResult" class="resultBox">
      <div class="exportBtnBox">
        <q-btn
          color="blue-10"
          class="exportBtn"
          label="导出"
          @click="exportTable"
        >
          <q-icon name="fa-solid fa-file-arrow-down" class="exportSVG" />
        </q-btn>
      </div>
      <q-table
        flat
        bordered
        dense
        separator="cell"
        table-header-class="bg-grey-4"
        :rows="rbrows"
        :columns="rbcolumns"
        row-key="NO"
        class="resultTable"
        :pagination="{ rowsPerPage: 50 }"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, toRaw } from "vue";
import { useUserStore } from "src/stores/modules/userStore";
import { useReportStore } from "src/stores/modules/reportStore";
import HeaderTitle from "src/components/HeaderTitle.vue";
import { jsonParse } from "src/utils/utils";
import { useQuasar, Loading, exportFile } from "quasar";

import { exportWorkerReportResult} from 'src/services/reportService'

// Search Box Requirements

const $q = useQuasar();

const goldTypeInfo = ref([]);
const showResult = ref(false);
const sDate = ref(null);
const eDate = ref(null);
const dateStart = ["2023.09.27", "2023.09.27", "2023.09.27"];
const dateEnd = ["2022.09.27", "2023.09.27", "2023.09.27"];

const deliverDate = ref("");
const completeDate = ref("");
const useUser = useUserStore();
const useReport = useReportStore();

let staffCode = null;
let userCode = null;
const reportType = "transaction";

const init = async () => {
  // get user data:
  staffCode = useUser.staffID;
  userCode = useUser.currentDept.userCode;

  if (staffCode && userCode) {
    // call api // get params: goldtype, datetimechoice
    const res = await useReport.getWorkerReportParams(
      reportType,
      staffCode,
      userCode
    );
    if (res) {
      console.log(res);
      const obj = res.goldNK.replace(/'/g, '"');
      const newobj = JSON.parse(obj.replace(/\\"/g, '"'));
      console.log(newobj);
      const goldNkArray = newobj.data;
      goldTypeInfo.value = [];
      for (let i = 0; i < goldNkArray.length; i++) {
        const { Nk, NkDesc } = goldNkArray[i];
        goldTypeInfo.value.push({
          goldType: `${Nk} (${NkDesc})`,
          isChosen: false,
          gold_type: `${Nk}`,
        });
      }
    } else {
      // error msg

      console.log("3", res);
    }
  }
};
init();

// Result Table
const rbcolumns = [
  {
    name: "NO",
    required: true,
    label: "序号",
    align: "left",
    field: "RowID",
    format: (val) => `${val}`,
    sortable: true,
  },
  {
    name: "dept",
    align: "center",
    label: "工人部门",
    field: "wrkdpt",
    sortable: true,
  },
  {
    name: "issueDate",
    align: "center",
    label: "发出日期",
    field: "out_date",
    sortable: true,
  },
  {
    name: "orderNo",
    align: "center",
    label: "生产单号",
    field: "sonum",
    sortable: true,
  },
  {
    name: "moldNo",
    align: "center",
    label: "设计编号",
    field: "designno",
    sortable: true,
  },
  {
    name: "goldType",
    align: "center",
    label: "金料成色",
    field: "stkcde",
    sortable: true,
  },
  { name: "qty", align: "center", label: "件数", field: "qty", sortable: true },
  {
    name: "netweight",
    align: "center",
    label: "发出净重",
    field: "out_fgwgt",
    sortable: true,
  },
  {
    name: "stoneNo",
    align: "center",
    label: "石粒数",
    field: "stoneqty",
    sortable: true,
  },
  {
    name: "stoneWeight",
    align: "center",
    label: "石重",
    field: "stonewgt",
    sortable: true,
  },
  {
    name: "incomeDate",
    align: "center",
    label: "收入日期",
    field: "in_date",
    sortable: true,
  },
  {
    name: "incomeWeight",
    align: "center",
    label: "收入净重",
    field: "in_fgwgt",
    sortable: true,
  },
  {
    name: "consumption",
    align: "center",
    label: "流程给耗",
    field: "scrap",
    sortable: false,
  },
  {
    name: "balance",
    align: "center",
    label: "结存",
    field: "balance",
    sortable: false,
  },
  {
    name: "sign2",
    align: "center",
    label: "核实签名",
    field: "sign2",
    sortable: false,
  },
];
// const rbcolumns = [
//   {
//     name: "NO",
//     required: true,
//     label: "序号",
//     align: "left",
//     field: (row) => row.no,
//     format: (val) => `${val}`,
//     sortable: true,
//   },
//   {
//     name: "dept",
//     align: "center",
//     label: "工人部门",
//     field: "dept",
//     sortable: true,
//   },
//   {
//     name: "issueDate",
//     align: "center",
//     label: "发出日期",
//     field: "issueDate",
//     sortable: true,
//   },
//   {
//     name: "orderNo",
//     align: "center",
//     label: "生产单号",
//     field: "orderNo",
//     sortable: true,
//   },
//   {
//     name: "moldNo",
//     align: "center",
//     label: "倒模编号",
//     field: "moldNo",
//     sortable: true,
//   },
//   {
//     name: "goldType",
//     align: "center",
//     label: "金料成色",
//     field: "goldType",
//     sortable: true,
//   },
//   { name: "qty", align: "center", label: "件数", field: "qty", sortable: true },
//   {
//     name: "netweight",
//     align: "center",
//     label: "发出净重",
//     field: "qty",
//     sortable: true,
//   },
//   {
//     name: "stoneNo",
//     align: "center",
//     label: "石粒数",
//     field: "stoneNo",
//     sortable: true,
//   },
//   {
//     name: "stoneWeight",
//     align: "center",
//     label: "石重",
//     field: "stoneWeight",
//     sortable: true,
//   },
//   {
//     name: "sign1",
//     align: "center",
//     label: "核实签名",
//     field: "sign1",
//     sortable: false,
//   },
//   {
//     name: "incomeDate",
//     align: "center",
//     label: "收入日期",
//     field: "incomeDate",
//     sortable: true,
//   },
//   {
//     name: "incomeWeight",
//     align: "center",
//     label: "收入净重",
//     field: "incomeWeight",
//     sortable: true,
//   },
//   {
//     name: "consumption",
//     align: "center",
//     label: "流程给耗",
//     field: "consumption",
//     sortable: false,
//   },
//   {
//     name: "balance",
//     align: "center",
//     label: "结存",
//     field: "balance",
//     sortable: false,
//   },
//   {
//     name: "sign2",
//     align: "center",
//     label: "核实签名",
//     field: "sign2",
//     sortable: false,
//   },
// ];

// Function: Download Table as xlxs file


// HARDCODE
const rbrows = ref([
  // {
  //   no: 1,
  //   dept: "B3T0098",
  //   issueDate: "2022.09.27",
  //   orderNo: "4800000377",
  //   moldNo: "609841C",
  //   goldType: "G750",
  //   qty: 5,
  //   netweight: 29.15,
  //   stoneNo: 5,
  //   stoneWeight: 0.235,
  //   sign1: " ",
  //   incomeDate: " ",
  //   incomeWeight: " ",
  //   consumption: " ",
  //   balance: " ",
  //   sign2: " ",
  // },
  // {
  //   no: 2,
  //   dept: "B3T0098",
  //   issueDate: "2022.09.27",
  //   orderNo: "4800002524",
  //   moldNo: "BA6671E",
  //   goldType: "G750",
  //   qty: 5,
  //   netweight: 28.12,
  //   stoneNo: 5,
  //   stoneWeight: 0.24,
  //   sign1: " ",
  //   incomeDate: " ",
  //   incomeWeight: " ",
  //   consumption: " ",
  //   balance: " ",
  //   sign2: " ",
  // },
]);

// Function: Toggle gold type choices
const toggleChoice = (idx) => {
  for(let i = 0; i<goldTypeInfo.value.length; i++){
    if(i==idx){
      goldTypeInfo.value[i].isChosen = true
    }else{
      goldTypeInfo.value[i].isChosen = false
    }
  }
};

// Function: Search
const searchInfo = async () => {
  // get search req
  let goldItems = goldTypeInfo.value.filter((g) => g.isChosen);
  goldItems = toRaw(goldItems);

  // call api
  let dateFrom = deliverDate.value.split(' ').join('T');
  let dateTo = completeDate.value.split(' ').join('T');

  if (goldItems.length == 0) {
    $q.notify({
      message: "请选择金成色选项get_report_result",
      color: "negative",
    });
    return;
  }
  if (dateFrom == "" || dateTo == "") {
    $q.notify({
      message: "请选择截数日期范围",
      color: "negative",
    });
    return;
  }

  rbrows.value = [];
  if (goldItems.length > 0) {
    let goldArr = [];
    for (let item of goldItems) {
      goldArr.push(item.gold_type);
    }

    // staffCode = '10001274'
    // userCode = 'F3F1274'
    // dateFrom = '2023-01-10T00:00:00'
    // dateTo = '2023-01-11T00:00:00'
    const goldType = goldArr.join();

    const res = await useReport.getWorkerReportResult(
      reportType,
      staffCode,
      userCode,
      goldType,
      dateFrom,
      dateTo
    );

    if (res.data.data) {
      const test = res.data.data.replace(/\\"/g,'"')
      console.log(test);
      const json = JSON.parse(test)
      console.log(json);
      rbrows.value = [...rbrows.value, ...json.data];
    }
    showResult.value = true;
  } else {
    // show error alert
    showResult.value = true;
  }
};

const exportTable = async () => {

  
  console.log("downloading worker transaction file... ");

  // get search req
  let goldItems = goldTypeInfo.value.filter((g) => g.isChosen);
  goldItems = toRaw(goldItems);

  
  // call api
  let dateFrom = deliverDate.value.split(' ').join('T');
  let dateTo = completeDate.value.split(' ').join('T');

  if (goldItems.length == 0) {
    $q.notify({
      message: "请选择金成色选项get_report_result",
      color: "negative",
    });
    return;
  }
  if (dateFrom == "" || dateTo == "") {
    $q.notify({
      message: "请选择截数日期范围",
      color: "negative",
    });
    return;
  }

  
  // rbrows.value = [];
  console.log(goldItems.length)
  if (goldItems.length > 0) {
    let goldArr = [];
    for (let item of goldItems) {
      goldArr.push(item.gold_type);
    }

    // staffCode = '10001274'
    // userCode = 'F3F1274'
    // dateFrom = '2023-01-10T00:00:00'
    // dateTo = '2023-01-11T00:00:00'
    const goldType = goldArr.join();
    
    try {
      Loading.show()
      console.log("call API")
      const res = await exportWorkerReportResult(
        reportType,
        staffCode,
        userCode,
        goldType,
        dateFrom,
        dateTo
      );
      if (res.status==200){
        const filename = "workerTransaction.csv"
        // const filename = res.headers['content-disposition'].split('filename=')[1].replace(/"/g, '');

        
      const status = exportFile(filename, res.data, {
        encoding: 'utf-8',
        mimeType: 'text/csv;',
        byteOrderMark: '\uFEFF'
      })

      if (status!=true){
        $q.notify({
          message: '导出失败',
          color: 'negative',
          timeout: 2000,
          position: "center",
        })
      }else{
        $q.notify({
          message: '导出成功',
          color: 'positive',
          timeout: 2000,
          position: "center",
        })
      }

      }
    } catch (error) {
      console.log(error);
    }
    Loading.hide()

  }


}

  
</script>

<style lang="scss">
.deliveryEnquiryPage {
  width: 90%;
  margin-left: auto;
  margin-right: auto;
  font-size: 1rem;
  @media (max-width: 480px) {
    font-size: 1rem;
  }

  .searchBox {
    margin-top: 20px;
    border-radius: 10px;
    padding: 5px 10px 10px 10px;
    width: 100%;
    background-color: rgba(255, 255, 255, 0.829);
    .sbTitle {
      width: 100%;
      font-weight: bold;
      margin-bottom: 5px;
      margin-top: 10px;
    }
    .gtBox {
      width: 100%;
      text-align: center;
      margin-top: 3px;
      .gtTitle {
        background-color: white;
        margin-top: 3px; // This will be deleted when choices box is in v-for
      }
      .gtBtn {
        background-color: #6456c8;
        margin-top: 3px; // This will be deleted when choices box is in v-for
      }
      .goldChosen {
        background-color: #b8aeff !important;
      }
    }
    .dateRangeBox {
      width: 100%;
      text-align: center;
      .drContent {
        margin-right: 5px;
        margin-left: 5px;
      }
    }
  }

  .searchBtnBox {
    margin-top: 15px;
    width: 100%;
    .searchBtn {
      width: 100%;
    }
  }

  .resultBox {
    margin-top: 10px;
    width: 100%;
    .exportBtnBox {
      margin-left: 10px;
      text-align: right;
      .exportBtn {
        font-size: 1rem;
        .exportSVG {
          margin-left: 5px;
        }
      }
    }
    .resultTable {
      width: 100%;
      margin-top: 10px;
    }
  }
}

.input-css {
  background-color: #fff;
}
</style>
